/** 注册所有的model */

import * as fs from "fs";
import * as commSvc from "../services/common.service";

export enum ENUM_ACTION {
  LIST = "LIST",
  ONE = "ONE",
  CREATE_ONE = "CREATE_ONE",
  CREATE_MANY = "CREATE_MANY",
  UPDATE = "UPDATE",
  DELETE = "DELETE",
}

export const ACTION = {
  READ: [ENUM_ACTION.LIST, ENUM_ACTION.ONE],
  READWRITE: [
    ENUM_ACTION.CREATE_ONE,
    ENUM_ACTION.CREATE_MANY,
    ENUM_ACTION.LIST,
    ENUM_ACTION.ONE,
    ENUM_ACTION.UPDATE,
    ENUM_ACTION.DELETE,
  ],
};

/** 资源注册参数 */
export interface IResourceRegisterParams {
  /** 资源名称 */
  name: string;
  /** 资源模型 */
  model: import("mongoose").Model<any>;
  /** 允许的动作 */
  action: commSvc.IAction[];
  /** 资源描述 */
  desc: string;
}

/** 资源权限管理 */
const resouceAuthManager = new Map<string, IResourceRegisterParams>();

// 注册资源模型
export const registerResouceModel = (res: IResourceRegisterParams) => {
  resouceAuthManager.set(res.model.modelName, res);
};

// 校验资源动作权限
export const checkResouceActionAuth = (
  resourceName: string,
  actionName: commSvc.IAction
) => {
  const { action } = resouceAuthManager.get(resourceName) || {};
  return action?.includes(actionName) ? true : false;
};

// 导出注册资源信息
export const getResouceRegisterInfo = () => {
  const resList = Array.from(resouceAuthManager.values());
  return resList
    .map((res) => {
      return {
        name: res.name,
        actions: res.action.toString(),
        desc: res.desc,
      };
    })
    .sort((a, b) => a.name.localeCompare(b.name));
};

// 导入所有model
const modelFiles = fs.readdirSync("./src/models", { withFileTypes: true });
modelFiles.forEach((file) => {
  if (file.name !== "index.ts" && !file.isDirectory()) import(`./${file.name}`);
});
